import os

import requests
from bs4 import BeautifulSoup
import random
import re
import json


def parse_items():
    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'max-age=0',
        'priority': 'u=0, i',
        'referer': 'https://www.google.com/',
        'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
        # 'cookie': '_gcl_au=1.1.1766823264.1757321387; _ga=GA1.1.1302017467.1757321388; OTGPPConsent=DBABLA~BVQVAAAAAAGA.QA; _ga_QWX66025LC=GS2.1.s1759113962$o3$g1$t1759114047$j59$l0$h0; filters-configs={"expanded":{"type":true,"license":true,"iconType":true},"group":[{"name":"type","show":true},{"name":"license","show":true},{"name":"iconType","show":true}],"show":false}; OptanonAlertBoxClosed=2025-09-29T02:47:31.320Z; OptanonConsent=isGpcEnabled=0&datestamp=Mon+Sep+29+2025+10%3A47%3A31+GMT%2B0800+(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)&version=202508.2.0&browserGpcFlag=0&isIABGlobal=false&hosts=&consentId=6eb3e82c-a8ff-4eff-8157-7a35cd27e894&interactionCount=2&isAnonUser=1&landingPath=NotLandingPage&GPPCookiesCount=1&groups=C0001%3A1%2CC0002%3A1%2CC0003%3A1%2CC0004%3A1%2CC0005%3A1&AwaitingReconsent=false&intType=1',
    }
    randint = random.randint(1, 100)
    response = requests.get(
        rf'https://zh.freepik.com/照片/8k高清壁纸/{randint}',
        headers=headers,
    )
    if response.status_code == 404:
        print("404，结束")
    soup = BeautifulSoup(response.text, 'html.parser')
    hrefs = soup.find_all('a', class_='block rounded-xl overflow-hidden')
    items = []
    for href in hrefs:
        match = re.search(r'_(\d+)\.htm', href.get('href'))
        if match:
            items.append({
                'alt': href.find('img').get('alt'),
                'download_resource': match.group(1),
                'src': href.find('img').get('src'),
            })
    print(f"共有{len(items)}个结果")
    print(items)
    return items


def get_origin_pic(item):
    headers = {
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'if-none-match': 'W/"xtjmeffkxkd1"',
        'priority': 'u=1, i',
        'referer': 'https://zh.freepik.com/%E7%85%A7%E7%89%87/8k%E9%AB%98%E6%B8%85%E5%A3%81%E7%BA%B8',
        'sec-ch-ua': '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
        # 'cookie': '_gcl_au=1.1.1766823264.1757321387; _ga=GA1.1.1302017467.1757321388; OTGPPConsent=DBABLA~BVQVAAAAAAGA.QA; filters-configs={"expanded":{"type":true,"license":true,"iconType":true},"group":[{"name":"type","show":true},{"name":"license","show":true},{"name":"iconType","show":true}],"show":false}; OptanonAlertBoxClosed=2025-09-29T02:47:31.320Z; _hjSession_1331604=eyJpZCI6ImIyNzY2ZGUxLWQxZjYtNDE1ZS05MzQyLWZkYzRlYjZkYmExOSIsImMiOjE3NTkxMTQwNTg4MTIsInMiOjAsInIiOjAsInNiIjowLCJzciI6MCwic2UiOjAsImZzIjoxLCJzcCI6MH0=; _hjHasCachedUserAttributes=true; sb-prefs={%22mode%22:%22anchored%22}; _hjSessionUser_1331604=eyJpZCI6IjJlNGQ3ZDMxLTFlYjYtNTU2My1iZWFhLTlmYzMxYzdlM2ZmZCIsImNyZWF0ZWQiOjE3NTkxMTQwNTg4MTEsImV4aXN0aW5nIjp0cnVlfQ==; _ga_QWX66025LC=GS2.1.s1759113962$o3$g1$t1759115510$j60$l0$h0; OptanonConsent=isGpcEnabled=0&datestamp=Mon+Sep+29+2025+11%3A11%3A51+GMT%2B0800+(%E4%B8%AD%E5%9B%BD%E6%A0%87%E5%87%86%E6%97%B6%E9%97%B4)&version=202508.2.0&browserGpcFlag=0&isIABGlobal=false&hosts=&consentId=6eb3e82c-a8ff-4eff-8157-7a35cd27e894&interactionCount=2&isAnonUser=1&landingPath=NotLandingPage&GPPCookiesCount=1&groups=C0001%3A1%2CC0002%3A1%2CC0003%3A1%2CC0004%3A1%2CC0005%3A1&AwaitingReconsent=false&intType=1&geolocation=%3B',
    }

    params = {
        'resource': items['download_resource'],
        'action': 'download',
        'locale': 'zh-HK',
    }

    response = requests.get('https://zh.freepik.com/api/regular/download', params=params, headers=headers)
    if response.status_code == 200:
        d = json.loads(response.text)
        print(f"url: {d['url']}")
        print(f"signedUrl: {d['signedUrl']}")
    if response.status_code == 429:
        print(f"要等{response.headers}秒")
    else:
        print(response.text)
        print(response.status_code)


def download_pic(d):
    # 指定保存目录
    save_dir = r"C:\Users\Administrator\Desktop\wallpaper"  # 你想保存的文件夹
    os.makedirs(save_dir, exist_ok=True)  # 自动创建目录（如果不存在）

    # 文件名可以自己定义，或者从 URL 里取
    filename = d["url"].split("?")[0].split("/")[-1]
    filepath = os.path.join(save_dir, filename)

    # 下载
    with requests.get(d["url"], stream=True) as r:
        r.raise_for_status()
        with open(filepath, "wb") as f:
            for chunk in r.iter_content(1024):
                f.write(chunk)

    print("下载完成:", filepath)


if __name__ == '__main__':
    parse_items()
